<template>
  <el-container style="flex-direction: column; height: 100vh;">
    <OwnerHeader :userInfo="userInfo" />
    <div class="forum-container">
      <!-- 浮动发帖按钮 -->
      <el-button class="float-post-btn" type="primary" icon="el-icon-plus" circle @click="showPostDialog = true">
      </el-button>

      <!-- 发帖对话框 -->
      <el-dialog title="发布新帖" :visible.sync="showPostDialog" width="600px">
        <el-form>
          <el-form-item label="内容" required>
            <el-input type="textarea" :rows="4" v-model="newPost.content" placeholder="请输入帖子内容">
            </el-input>
          </el-form-item>
        </el-form>
        <span slot="footer">
          <el-button @click="showPostDialog = false">取消</el-button>
          <el-button type="primary" @click="publishPost">发布</el-button>
        </span>
      </el-dialog>

      <!-- 帖子列表 -->
      <div class="post-list">
        <div v-for="post in posts" :key="post.id" class="post-card">
          <div class="post-header">
            <el-avatar :size="40" :src="post.image"></el-avatar>
            <div class="post-author">
              <span class="author-name">{{ post.username }}</span>
              <span class="post-time">{{ formatTime(post.releaseTime) }}</span>
            </div>
          </div>
          <!-- 帖子内容 -->
          <div class="post-content">{{ post.content }}</div>

          <div class="interaction">
            <!-- 点赞 -->
            <el-button type="text" :icon="likes.includes(post.id) ? 'el-icon-star-on' : 'el-icon-star-off'"
              :style="{ color: likes.includes(post.id) ? '#f56c6c' : '#999' }" @click="toggleLike(post)">
              {{ post.likes }}
            </el-button>
            <!-- 评论 -->
            <el-button type="text" icon="el-icon-chat-dot-round" @click="toggleComments(post)">
              评论 {{ (post.comments || []).length }}
            </el-button>
          </div>

          <!-- 评论区域 -->
          <div v-show="post.showComments" class="comment-section">
            <!-- 评论输入框及回复区域 -->
            <div class="comment-input">
              <el-input v-model="newComment"
                :placeholder="post.replyingTo ? `回复 @${post.replyingTo.author}:` : '写下你的评论...'"
                @focus="currentPostId = post.id" style="height: 40px;">
              </el-input>
              <el-button type="primary" class="submit-btn" @click="submitComment(post)" :disabled="!newComment.trim()"
                style="height: 40px;">
                {{ post.replyingTo ? '发送回复' : '提交评论' }}
              </el-button>
            </div>

            <!-- 评论列表 -->
            <div v-for="comment in post.comments" :key="comment.id" class="comment-item" style="text-align: left;"
              @click="mentionUser(comment)">
              <div class="comment-header">
                <el-avatar :size="32" :src="comment.image"></el-avatar>
                <div class="comment-author">
                  <span class="author-name">{{ comment.username }}</span>
                  <span class="comment-time">{{ formatTime(comment.releaseTime) }}</span>
                </div>
              </div>
              <div class="comment-content">{{ comment.content }}</div>


            </div>
          </div>
        </div>
      </div>
    </div>
  </el-container>
</template>

<script>
import OwnerHeader from '@/components/owner_components/OwnerHeader.vue';
import { parseJwt } from '@/utils/parseJWT';
import service from '@/utils/request';

export default {
  components: {
    OwnerHeader
  },
  data() {
    return {
      userInfo: {}, // 初始化避免 undefined
      showPostDialog: false,
      currentPostId: null,
      mentionedUser: null,
      likes: [], //点赞postId
      newPost: {
        content: ''
      },
      newComment: '',
      posts: [
        {
          id: 0,
          userId: 0,
          content: '',
          username: '',
          image: '',
          releaseTime: '',
          likes: 0,
          liked: false,
          showComments: false,
          comments: [
            {
              id: 0,
              postId: 0,
              userId: 0,
              username: '',
              image: '',
              content: '',
              releaseTime: '',
            }
          ]
        }
      ]
    }
  },
  mounted() {
    const token = localStorage.getItem('token');
    if (token) {
      this.userInfo = parseJwt(token).payload || {}; // 防止 null 错误
    }
    this.getPosts();
    this.getLikes();
  },
  methods: {
    getLikes() {
      service.post('/api/user/forum/getLikes', {
        userId: this.userInfo.id
      }).then(response => {
          const result = response.data;
          if (result.code !== 1) {
            this.$message.error(result.msg);
            return;
          }
          this.likes = result.data;
        })
        .catch(error => {
          this.$message.error('获取点赞失败');
          console.error(error);
        })
    },
    getPosts() {
      service.get('/api/user/forum/getPosts')
        .then(response => {
          const result = response.data;
          if (result.code !== 1) {
            this.$message.error(result.msg);
            return;
          }

          // 初始化帖子数据，添加响应式属性
          this.posts = result.data.map(post => ({
            ...post,
            showComments: false,
            comments: post.comments || [] // 初始评论数据
          }));

          // 并行获取所有帖子的评论
          const commentPromises = this.posts.map(post =>
            service.get(`/api/user/forum/getComments/${post.id}`)
              .then(commentResponse => {
                const commentResult = commentResponse.data;
                if (commentResult.code === 1) {
                  // 更新评论数据，Vue会自动检测数组变更
                  post.comments = commentResult.data;
                } else {
                  this.$message.error(commentResult.msg);
                }
              })
              .catch(error => {
                this.$message.error('获取评论失败');
                console.error(error);
              })
          );

          return Promise.all(commentPromises);
        })
        .then(() => {
          // 所有数据加载完成，可执行后续操作
          console.log('所有帖子及评论已加载:', this.posts);
        })
        .catch(error => {
          if (!error.response) { // 避免重复显示错误信息
            this.$message.error('获取帖子失败');
          }
          console.error(error);
        });
    },

    formatTime(timestamp) {
      return new Date(timestamp).toLocaleString();
    },

    publishPost() {
      service.post('/api/user/forum/addPost', {
        userId: this.userInfo.id,
        content: this.newPost.content,
      }).then(response => {
        const result = response.data;
        if (result.code !== 1) {
          this.$message.error(result.msg);
          return;
        }
        this.getPosts();
      }).catch(error => {
        this.$message.error('发布失败');
      })

      this.showPostDialog = false;
      this.newPost = { title: '', content: '' };
    },

    toggleLike(post) {
      if (this.likes.includes(post.id)) {
        service.post('/api/user/forum/deleteLike', {
          postId: post.id,
          userId: this.userInfo.id
        }).then(response => {
          const result = response.data;
          if (result.code !== 1) {
            this.$message.error(result.msg);
            return;
          }
          this.getPosts();
          this.getLikes();
        }).catch(error => {
          this.$message.error('取消点赞失败');
        });
      } else {
        service.post('/api/user/forum/addLike', {
          postId: post.id,
          userId: this.userInfo.id
        }).then(response => {
          const result = response.data;
          if (result.code !== 1) {
            this.$message.error(result.msg);
            return;
          }
          this.getPosts();
          this.getLikes();
        }).catch(error => {
          this.$message.error('点赞失败');
        })
      }
    },

    toggleComments(post) {
      post.showComments = !post.showComments;
      this.currentPostId = post.id;
    },

    mentionUser(comment) {
      const pattern = /^@\S+：\s*/;
      if (pattern.test(this.newComment))
        this.newComment = this.newComment.replace(pattern, `@${comment.username}： `);
      else
        this.newComment = `@${comment.username}： ` + this.newComment;
    },

    submitComment(post) {
      service.post('/api/user/forum/addComment', {
        postId: post.id,
        userId: this.userInfo.id,
        content: this.newComment,
      }).then(response => {
        const result = response.data;
        if (result.code !== 1) {
          this.$message.error(result.msg);
          return;
        }
        this.newComment = '';
        this.getPosts();
        // 添加评论到帖子中
      }).catch(error => {
        this.$message.error('添加评论失败');
        console.error(error);
      });
    }
  }
}
</script>

<style scoped>
/* 全局布局设置 */
.forum-container {
  direction: ltr;
  flex: 1;
  width: 80%;
  margin: 0 auto;
  padding: 20px;
  overflow-y: auto;
}

/* 浮动按钮 */
.float-post-btn {
  position: fixed;
  right: 40px;
  bottom: 40px;
  width: 56px;
  height: 56px;
  font-size: 24px;
  z-index: 1000;
}

/* 帖子卡片样式 */
.post-card {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
  padding: 20px;
}

/* 帖子头部 */
.post-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.post-author {
  margin-left: 15px;
}

.author-name {
  display: block;
  font-weight: 500;
  color: #303133;
}

.post-time {
  font-size: 0.85em;
  color: #999;
}

/* 帖子内容 */
.post-content {
  text-align: left;
  color: #606266;
  line-height: 1.6;
  margin: 15px 0;
  white-space: pre-wrap;
}

/* 互动区域 */
.interaction {
  border-top: 1px solid #eee;
  padding-top: 15px;
  margin-top: 15px;
  display: flex;
  gap: 20px;
}

/* 调整互动按钮样式 */
.interaction .el-button {
  font-size: 16px;
  /* 调大文字 */
  padding: 8px 12px;
  /* 增加点击区域 */
  transform: scale(1.1);
  /* 整体放大10% */
  margin-right: 15px;
  /* 增加按钮间距 */
}

/* 调大图标 */
.interaction [class*="el-icon"] {
  font-size: 20px;
  vertical-align: middle;
  margin-right: 6px;
}

/* 悬停效果增强 */
.interaction .el-button:hover {
  transform: scale(1.15);
  transition: all 0.2s ease;
}

/* 评论区域 */
.comment-section {
  margin: 20px;
  border-top: 1px solid #f0f2f5;
  padding-top: 20px;
}

/* 评论输入框 */
.comment-input {
  display: flex;
  margin: 15px 0;
}

/* 输入框容器 */
.comment-input :deep(.el-input) {
  flex: 1;
  margin-right: -1px;
  /* 消除边框重叠 */
}

/* 输入框本体 */
.comment-input :deep(.el-input__inner) {
  height: 40px;
  border-radius: 4px 0 0 4px;
  border-right: none;
  padding-right: 8px;
  vertical-align: middle;
}

/* 按钮调整 */
.submit-btn {
  height: 40px;
  border-radius: 0 4px 4px 0;
  padding: 12px 20px;
  display: inline-flex;
  align-items: center;
  border-left: none;
}

/* 保持焦点状态连贯 */
.comment-input:focus-within {
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.3);
}

/* 评论项 */
.comment-input {
  display: flex;
  align-items: center;
  /* 确保输入框和按钮在同一行垂直居中 */
  margin: 15px;
}

.comment-input :deep(.el-textarea) {
  flex: 1;
  /* 输入框占据剩余空间 */
  margin-right: 10px;
  /* 输入框和按钮之间的间距 */
}

.comment-input :deep(.el-textarea__inner) {
  border-radius: 4px;
  resize: none;
  padding: 12px;
}

.comment-input :deep(.el-input-group__append) {
  display: flex;
  align-items: center;
  padding: 0;
}

.submit-btn {
  min-width: 60px;
  /* 设置最小宽度防止按钮收缩 */
  border-radius: 4px;
  padding: 0 16px;
  background-color: #409EFF;
  color: #fff;
  border: 1px solid #409EFF;
}

/* 回复项 */
.reply-item {
  margin-left: 38px;
  /* 与评论内容对齐 */
  margin-top: 8px;
  background: #f8f9fa;
  /* 更浅的背景色 */
  padding: 8px 12px;
  border-radius: 4px;
  display: inline-block;
}

.reply-author {
  color: #409EFF;
  cursor: pointer;
}

.reply-author:hover {
  text-decoration: underline;
}

/* 用户提及样式 */
.author-name,
.reply-author {
  color: #409EFF;
  cursor: pointer;
}

.author-name:hover,
.reply-author:hover {
  text-decoration: underline;
}

/* 评论头部布局 */
.comment-header {
  display: flex;
  align-items: center;
  /* 垂直居中 */
  gap: 12px;
  /* 头像和文字间距 */
  margin-bottom: 8px;
}

.comment-author {
  display: flex;
  flex-direction: column;
  /* 姓名和时间垂直排列 */
}

/* 当需要姓名和时间水平排列时 */
.comment-author.horizontal {
  flex-direction: row;
  align-items: baseline;
  gap: 8px;
}

/* 添加评论分割线 */
.comment-item {
  border-bottom: 1px solid #eee;
  padding-bottom: 16px;
  margin-bottom: 16px;
}

/* 最后一个评论不需要分割线 */
.comment-item:last-child {
  border-bottom: none;
  padding-bottom: 0;
  margin-bottom: 0;
}
</style>